package sign

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"os"
)

func GenerateRsaKey() error {

	// 生成私钥
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return err
	}

	derPrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)

	privateKeyBlock := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: derPrivateKey,
	}

	// 将私钥写入文件中
	privateKeyFile, err := os.Create("./conf/private.pem")
	if err != nil {
		return err
	}

	defer privateKeyFile.Close()
	pem.Encode(privateKeyFile, privateKeyBlock)

	// 生成公钥
	publicKey := privateKey.PublicKey

	derPublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		return err
	}

	publicKeyBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: derPublicKey,
	}

	// 将公钥写入文件中
	publicKeyFile, err := os.Create("./conf/public.pem")
	if err != nil {
		return err
	}

	defer publicKeyFile.Close()
	pem.Encode(publicKeyFile, publicKeyBlock)
	return nil

}

func Sign(data []byte, filename string) (string, error) {
	privateKey, err := ReadParsePrivaterKey(filename)
	h := sha256.New()
	h.Write(data)
	hash := h.Sum(nil)
	signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(signature), nil
	//return hex.EncodeToString(signature), nil

}

func Verify(signature string, data []byte, filename string) bool {
	publicKey, err := ReadParsePublicKey(filename)
	h := sha256.New()
	h.Write(data)
	hash := h.Sum(nil)
	decodedSignature, err := base64.StdEncoding.DecodeString(signature)
	//decodedSignature, err := hex.DecodeString(signature)
	if err != nil {
		return false
	}

	err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hash, decodedSignature)
	if err != nil {
		return false
	}
	return true

}

// ReadParsePublicKey 读取公钥文件，解析出公钥对象
func ReadParsePublicKey(filename string) (*rsa.PublicKey, error) {
	// 1、读取公钥文件，获取公钥字节
	publicKeyBytes, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	// 2、解码公钥字节，生成加密块对象
	block, _ := pem.Decode(publicKeyBytes)
	if block == nil {
		return nil, errors.New("公钥信息错误！")
	}
	// 3、解析DER编码的公钥，生成公钥接口
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	// 4、公钥接口转型成公钥对象
	publicKey := publicKeyInterface.(*rsa.PublicKey)
	return publicKey, nil
}

// ReadParsePrivaterKey 读取私钥文件，解析出私钥对象
func ReadParsePrivaterKey(filename string) (*rsa.PrivateKey, error) {
	// 1、读取私钥文件，获取私钥字节
	privateKeyBytes, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	// 2、对私钥文件进行编码，生成加密块对象
	block, _ := pem.Decode(privateKeyBytes)
	if block == nil {
		return nil, errors.New("私钥信息错误！")
	}
	// 3、解析DER编码的私钥，生成私钥对象
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return privateKey, nil

}
